package dao;

import dto.Player;

import java.io.*;
import java.util.HashMap;
import java.util.List;

public class DataDisk implements Data{

    private final String filepath;

    public DataDisk(HashMap<String ,String > param){
        this.filepath = param.get("path");
    }

    @Override
    public List<Player> loadData() {
        ObjectInputStream ois = null;
        List<Player> players = null;
        try {
            ois = new ObjectInputStream(new FileInputStream(filepath));
            players = (List<Player>)ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            try{
                ois.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return players;
    }
    @Override
    public void saveData(Player pla) {
        //先取出数据，
        List<Player> players = this.loadData();
        //判断记录是否超过五条，如果超过，去掉分数低的
        //追加新纪录
        players.add(pla);
        //重新写入
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream(filepath));
            oos.writeObject(players);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                oos.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
